﻿//#define  CUSTOM_UI  //自定义测试结果界面
//#define SQL_ENABLE 

#region using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using System.Threading;
using System.Reflection;

using Testpad.BTS;
using Kuge.AppSetting;

#endregion

namespace BTS6000
{
    public partial class frmMain : Form
    {

        #region Class

        public class DataItem
        {
            public Kuge.Protocol.RS232.Tag Tag;
            public Testpad.BTS.Data Data;

        }

        #endregion

        #region Global

        /// <summary>
        /// BTS实例.
        /// 实例化之后,其它窗体可以调用
        /// Testpad.BTS BTS_Instance = Testpad.BTS.Instance;
        /// 获取当前唯一实例
        /// </summary>
        private Testpad.BTS.IBTS6000 BTS_Instance;

        /// <summary>
        /// 参数设置界面
        /// </summary>
        private Testpad.BTS.Editor ParameterEditor;

        /// <summary>
        /// 轮询方式的数据队列
        /// </summary>
        private System.Collections.Concurrent.ConcurrentQueue<DataItem> DataQueue = new System.Collections.Concurrent.ConcurrentQueue<DataItem>();

        private float Temperature;

        private int TotalReceived = 0;
        private int TotalPassed = 0;
        private int TotalFailed = 0;

        private int MDBInserted = 0;
        private int MDBFailed = 0;

        internal StringBuilder Barcode = new StringBuilder();

        internal readonly StringResources SR;

        private const string SEC_Database = "Database";
#if SQL_ENABLE
        private SQL Sql; 
#endif

        private readonly string DataDirectory;

#if CUSTOM_UI
        private frmData DataWindow = new frmData();
#endif

        #endregion

        #region frmMain

        public frmMain()
        {
            InitializeComponent();

            this.Icon = Properties.Resources.Tools;

            SR = new global::StringResources();

#if !SQL_ENABLE
            toolStripSeparator4.Visible = false;
            mSQLServerSetup.Visible = false;
            mHistory.Visible = false;
            mSQL_LoadParameter.Visible = false;
#endif

            DataDirectory = INI.GetString(Kuge.Resources.Text.Local, Kuge.Resources.Text.Path, @"D:\BTS6000_Database");

#if OFFLINE
            //只允许脱机使用
            Kuge.Message.Online = false;  
#else
            //只允许联网使用
            Kuge.Message.Online = true;
#endif

            ParameterEditor = new Testpad.BTS.Editor(true, true);
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            if (Language.CurrentLCID == Language.LCID.CHT)
            {
                Language.ToCHT(this);
            }

            Kuge.Message.PopupMessage("Loading...", this, 1000);

#if SQL_ENABLE
            Sql = new BTS6000.SQL(); 
#endif

            try
            {
                if (System.IO.Directory.Exists(DataDirectory) == false)
                {
                    System.IO.Directory.CreateDirectory(DataDirectory);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (Language.CurrentLCID != Language.LCID.ENG)
            {
                mHistoryEnglish.Visible = true;
            }
            try
            {
                ParameterEditor.SaveToClick += ParameterEditor_SaveToClick;
                ParameterEditor.DownloadClick += ParameterEditor_DownloadClick;
                ParameterEditor.StartClick += ParameterEditor_StartClick;
                //可以根据权限来显示和隐藏某些功能
                ParameterEditor.SaveDisable = false;//是否可以保存参数
                ParameterEditor.OpenDisable = false;//是否可以打开参数
                ParameterEditor.DownloadDisable = false;//是否可以下载参数
                ParameterEditor.ReadOnly = false;//是否可以修改参数
                ParameterEditor.Icon = this.Icon;
                ParameterEditor.CompareWithHistoryVisiable = true;
            }
            catch
            {
            }

            try
            {
                BTS_Instance = new Testpad.BTS.BTS6000();
                BTS_Instance.ParameterChanged += BTS_Instance_ParameterChanged;
                BTS_Instance.Heartbeat += BTS_Instance_Heartbeat;
                BTS_Instance.Synchronization += BTS_Instance_Synchronization;
                BTS_Instance.MessageReceived += BTS_Instance_MessageReceived;
                BTS_Instance.ProgressReceived += BTS_Instance_ProgressReceived;
                BTS_Instance.DataClear += BTS_Instance_DataClear;
                BTS_Instance.DataReceived += BTS_Instance_DataReceived;
                BTS_Instance.TemperatureUpdated += BTS_Instance_TemperatureUpdated;

                BTS_Instance.BarcodeReceived += BTS_Instance_BarcodeReceived;
#if CUSTOM_UI
                DataWindow.MdiParent = this;
                DataWindow.WindowState = FormWindowState.Maximized;
                DataWindow.Show();
#else
                BTS_Instance.ShowData(this);
                BTS_Instance.BarcodePressed += BTS_Instance_BarcodePressed;
#endif
                //其它窗体可以调用Testpad.BTS BTS_Instance = Testpad.BTS.BTS6000.Instance;获取当前唯一实例


                ParameterEditor.LoadXML(new FileInfo(@"D:\a.xml"));
                BTS_Instance.Parameter_Download(ParameterEditor.Parameter);
            }
            catch
            {
            }

            T_Refresh.Enabled = true;

#if SQL_ENABLE
            ConnectSQL(); 
#endif

            mScanAfterTest.Checked = INI.GetBoolean(Kuge.Resources.Text.Default, "ScanAfterTest");
            Lab_Version.Text = "V" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            /**************************************************************
            小技巧:

            //1.通过代码直接修改参数的方法:
            ParameterEditor.Parameter.Steps.Step1 = Step.IR;//步骤1设为"交流阻抗"
            ParameterEditor.Parameter.OCV1.Minimum = (float)3.8;//开路电压1的下限设为3.8V
            ParameterEditor.Parameter.Option.BarcodeLength = 13;//"选项"参数里的"条码长度"设为13

            //2.用代码加载XML参数文件内容
            Testpad.BTS.Editor.Instance.FromXML(txtOutput.Text);//加载
            Testpad.BTS.BTS6000.Instance.Parameter_Download(Testpad.BTS.Editor.Instance.Parameter);//下载到设备中

            //3.导出当前参数的XML文件内容
            Testpad.BTS.Editor.Instance.ToXML()
            ***************************************************************/
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;

            INI.Set(Kuge.Resources.Text.Default, "ScanAfterTest", mScanAfterTest.Checked);

            e.Cancel = false;
        }

        #region ConnectSQL
#if SQL_ENABLE
        private void ConnectSQL()
        {
            System.Threading.Tasks.Task.Factory.StartNew
                (
                    () =>
                    {
                        if (INI.Get<bool>(Kuge.Resources.Text.SQLServer, Kuge.Resources.Text.Enable, false.ToString()))
                        {
                            string ds, ic, ui, pw;
                            bool local;

                            ds = INI.Get<string>(Kuge.Resources.Text.SQLServer, Kuge.Resources.Text.DataSource, string.Empty);
                            ic = INI.Get<string>(Kuge.Resources.Text.SQLServer, Kuge.Resources.Text.InitialCatalog, string.Empty);
                            ui = INI.Get<string>(Kuge.Resources.Text.SQLServer, Kuge.Resources.Text.UserID, string.Empty);
                            pw = INI.GetCiphertext(Kuge.Resources.Text.SQLServer, Kuge.Resources.Text.Password);
                            local = INI.GetBoolean(Kuge.Resources.Text.SQLServer, Kuge.Resources.Text.Local);

                            Sql.Connect(ds, ic, ui, pw, local);
                        }
                    }
                );
        } 
#endif 
        #endregion

        #endregion

        #region Menu

        private void MainMenu_ItemAdded(object sender, ToolStripItemEventArgs e)
        {
            if (string.IsNullOrEmpty(e.Item.Text))
            {
                e.Item.Visible = false;
            }
        }

        private void mReadParameter_Click(object sender, EventArgs e)
        {
            if (Language.CurrentLCID == Language.LCID.ENG)
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
            }
            else
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CN");
            }

            //可以根据权限来显示和隐藏某些功能
            ParameterEditor.SaveDisable = true;//是否可以保存参数
            ParameterEditor.OpenDisable = false;//是否可以打开参数
            ParameterEditor.DownloadDisable = false;//是否可以下载参数
            ParameterEditor.ReadOnly = true;//是否可以修改参数
            ParameterEditor.AutoSave = true;//自动保存到ParameterEdit.cfg
            ParameterEditor.ShowDialog();
        }

        private void mModifyParameter_Click(object sender, EventArgs e)
        {
            if (Language.CurrentLCID == Language.LCID.ENG)
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
            }
            else
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CN");
            }

            //可以根据权限来显示和隐藏某些功能
            ParameterEditor.SaveDisable = false;//是否可以保存参数
            ParameterEditor.OpenDisable = false;//是否可以打开参数
            ParameterEditor.DownloadDisable = false;//是否可以下载参数
            ParameterEditor.ReadOnly = false;//是否可以修改参数
            ParameterEditor.AutoSave = true;//自动保存到ParameterEdit.cfg
            ParameterEditor.ShowDialog();
        }

        private void mParameterXML_Click(object sender, EventArgs e)
        {
            if (ParameterEditor != null)
            {
                //ParameterEditor.ToXML():导出到XML字符串,可以存到SQL SERVER等数据库中,以实现参数集中管理
                //ParameterEditor.FromXML(xmlString):可以从SQL SERVER中导入
                //参数内容比较多,所以数据库必须尽可能用大字段来保存XML内容
                //除了XML版本之外,还有二进制版本,但只能以文件的形式加载和保存
                //txtData.Text = ParameterEditor.ToXML();
            }
        }

        private void mResetProbeCounter_Click(object sender, EventArgs e)
        {
            if (BTS_Instance == null)
            {
                MessageBox.Show(SR.DeviceIsNotReady, SR.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                //reset the probe counter
                frmResetProbe f = new frmResetProbe();
                f.ShowDialog();
            }
        }

        private void mUpgrade_Click(object sender, EventArgs e)
        {
            if (BTS_Instance == null)
            {
                MessageBox.Show(SR.DeviceIsNotReady, SR.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                //弹出升级固件窗口
                BTS_Instance.Upgrade();
            }
        }

        private void mStart_Click(object sender, EventArgs e)
        {
            if (BTS_Instance == null)
            {
                MessageBox.Show(SR.DeviceIsNotReady, SR.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                //Start the 1st Channel
                BTS_Instance.Start(1);
            }
        }

        private void mCHn_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem Item = sender as ToolStripMenuItem;
            if (Item != null)
            {
                int CH;
                if (int.TryParse(Item.Text, out CH))
                {
                    BTS_Instance.LEDFlashing(CH);
                }
            }
        }

        private void mInitialize_Click(object sender, EventArgs e)
        {
            if (BTS_Instance == null)
            {
                MessageBox.Show(SR.DeviceIsNotReady, SR.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                //启动指定串口号的设备
                BTS_Instance.Initialize();
            }
        }

        private void mSQLServerSetup_Click(object sender, EventArgs e)
        {
            frmSQL_Setup f = new frmSQL_Setup();
            if (f.ShowDialog() == DialogResult.OK)
            {
#if SQL_ENABLE
                ConnectSQL(); 
#endif
            }
        }

        private void mSimplifiedChinese_Click(object sender, EventArgs e)
        {
            INI.Set("Default", "Language", "CHS");
        }

        private void mEnglish_Click(object sender, EventArgs e)
        {
            INI.Set("Default", "Language", "ENG");
        }

        private void mTraditionalChinese_Click(object sender, EventArgs e)
        {
            INI.Set("Default", "Language", "CHT");
        }

        #region History

        private void mHistory_Click(object sender, EventArgs e)
        {
#if SQL_ENABLE
            frmSQL_Search f = new frmSQL_Search(Language.CurrentLCID != Language.LCID.ENG);
            f.Show(); 
#endif
        }

        private void mHistoryEnglish_Click(object sender, EventArgs e)
        {
            frmSQL_Search f = new frmSQL_Search(false);
            f.Show();
        }

        private void mSQL_LoadParameter_Click(object sender, EventArgs e)
        {
            frmSQL_LoadParameter f = new BTS6000.frmSQL_LoadParameter();
            f.ShowDialog();
        }

        #endregion

        private void mCalbration_Click(object sender, EventArgs e)
        {
            if (BTS_Instance == null)
            {
                MessageBox.Show(SR.DeviceIsNotReady, SR.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                BTS_Instance.ShowCalibration();
            }
        }

        #endregion

        #region Parameter

        /// <summary>
        /// 参数设置界面点击"保存到..."时产生的事件,可以在此处编写代码,
        /// 将参数保存到服务器
        /// </summary>
        /// <param name="xml"></param>
        private void ParameterEditor_SaveToClick(string xml)
        {
            try
            {
                if (INI.Get<bool>(Kuge.Resources.Text.SQLServer, Kuge.Resources.Text.Enable, false.ToString()))
                {
                    frmSQL_SaveParameter f = new frmSQL_SaveParameter(xml);

                    f.ShowDialog();
                }
                else
                {
                    MessageBox.Show("SQL Server:" + SR.NotConnected, SR.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, SR.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 设置参数窗口的"下载"参数界面
        /// </summary>
        private void ParameterEditor_DownloadClick()
        {
            if (BTS_Instance == null)
            {
                MessageBox.Show("BTS_Instance==null!", SR.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                //Download Parameter
                BTS_Instance.Parameter_Download(ParameterEditor.Parameter);
                mStart.Enabled = true;
            }
        }

        /// <summary>
        /// 设置参数窗口的"启动"按钮事件
        /// </summary>
        private void ParameterEditor_StartClick()
        {
            if (BTS_Instance == null)
            {
                MessageBox.Show("BTS_Instance==null!", SR.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                //Starting Channel 1
                BTS_Instance.Start(BTS_Instance.Ports[0]);
            }
        }

        #endregion

        #region Events

        /// <summary>
        /// 参数发生变化时产生的事件
        /// </summary>
        /// <param name="items"></param>
        private void BTS_Instance_ParameterChanged(ProjectItemCollection items)
        {
        }

        /// <summary>
        /// 设备发来的心跳数据,可以判断是否需要升级固件
        /// </summary>
        /// <param name="tag"></param>
        private void BTS_Instance_Heartbeat(Kuge.Protocol.RS232.Tag tag)
        {
#if !CUSTOM_UI
            if (BTS_Instance.FirmwareID == null)
            {
                BTS_Instance.AppendInformationItem("Normal.F407", SR.FileNotFound, Color.Red);
            }
            else
            {
                string s = string.Format("{0} {1} {2}", SR.Channel, tag.Channel, SR.Firmware);
                if (tag.FirmwareID == BTS_Instance.FirmwareID)
                {
                    BTS_Instance.AppendInformationItem(s, SR.NoNeedUpgrade, Color.Green);

                    //Battery Voltage,当前电池电压
                    //Console.WriteLine("Voltage:{0}",tag.Voltage); 
                }
                else
                {
                    BTS_Instance.AppendInformationItem(s, SR.PleaseUpgrade, Color.Red);

                    //Automatic Update
                    //弹出升级固件窗口
                    BTS_Instance.Upgrade(true);
                }
            }
#endif
        }

        /// <summary>
        /// 参数同步时发生的事件
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="state"></param>
        private void BTS_Instance_Synchronization(Kuge.Protocol.RS232.Tag tag, bool? state)
        {
#if !CUSTOM_UI
            string s = string.Format("{0} {1} {2}", SR.Channel, tag.Channel, SR.Parameter);
            if (state == true)
            {
                BTS_Instance.AppendInformationItem(s, SR.Synchronized, Color.Green);
            }
            else if (state == false)
            {
                BTS_Instance.AppendInformationItem(s, SR.Synchronizing, Color.Red);
            }
            else
            {
                BTS_Instance.AppendInformationItem(s, SR.Unsynchronized, Color.Red);
            }
#endif
        }

        /// <summary>
        /// 接收到文本信息时产生的事件
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="msg"></param>
        private void BTS_Instance_MessageReceived(Kuge.Protocol.RS232.Tag tag, string msg)
        {
            //ShowMessage(tag, msg);
        }

        /// <summary>
        /// 接收到测试进度时产生的事件
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="progress"></param>
        /// <param name="item"></param>
        private void BTS_Instance_ProgressReceived(Kuge.Protocol.RS232.Tag tag, double progress, string item)
        {
            //ShowMessage(tag, progress, item);
            Console.WriteLine(item);
        }

        /// <summary>
        /// 请清除显示
        /// </summary>
        /// <param name="tag"></param>
        private void BTS_Instance_DataClear(Kuge.Protocol.RS232.Tag tag)
        {
            //ShowMessage(tag, "Clear Screen");
        }

        /// <summary>
        /// Do not deal with time-consuming code here
        /// 数据接收事件,请不要在此处处理数据,以免占用太多时间
        /// </summary>
        /// <param name="dat"></param>
        private void BTS_Instance_DataReceived(Testpad.BTS.Data dat)
        {
            Kuge.Protocol.RS232.Tag tag = dat.Tag as Kuge.Protocol.RS232.Tag;
            if (tag != null)
            {
                DataItem itm = new DataItem();
                itm.Tag = tag;
                itm.Data = dat;
                DataQueue.Enqueue(itm);
            }

            System.Threading.Interlocked.Increment(ref TotalReceived);
            if (dat.AllPassed)
            {
                System.Threading.Interlocked.Increment(ref TotalPassed);
            }
            else
            {
                System.Threading.Interlocked.Increment(ref TotalFailed);
            }

#if !CUSTOM_UI
            BTS_Instance.AppendInformationItem(SR.Total, TotalReceived);
            BTS_Instance.AppendInformationItem(SR.Passed, TotalPassed);
            BTS_Instance.AppendInformationItem(SR.Failed, TotalFailed);
#endif
        }

        /// <summary>
        /// 温度更新事件(使用USB温度器才会产生)
        /// </summary>
        /// <param name="temperature"></param>
        private void BTS_Instance_TemperatureUpdated(float temperature)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action<float>(BTS_Instance_TemperatureUpdated), temperature);
                }
                else
                {
                    Temperature = temperature;
                    if ((temperature > -50) && (temperature < 50))
                    {
                        mTemperature.Text = string.Format("{0:F1}℃", temperature);
                    }
                    else
                    {
                        mTemperature.Text = "@";
                    }
                }
            }
            catch
            {
            }
        }

        private void BTS_Instance_BarcodeReceived(int channel, string portname, string barcode)
        {
            // BTS_Instance.SendBarcode(portname, barcode);
#if !CUSTOM_UI
            BTS_Instance_BarcodePressed(barcode.Trim());
#endif
        }

#if !CUSTOM_UI
        /// <summary>
        /// 数据显示界面扫条码时产生的事件
        /// </summary>
        /// <param name="barcode"></param>
        private void BTS_Instance_BarcodePressed(string barcode)
        {
            if (barcode == "") return;
            if ((BTS_Instance!=null) && (ParameterEditor!=null) && (ParameterEditor.Parameter!=null))
            {
                if(BarcodeRuleCheck(ParameterEditor.Parameter.Option.BarcodeRule,barcode))
                {
                    try
                    {
                        int channel = 1;
                        bool isok;
                        isok=BTS_Instance.SendBarcode(channel, barcode);
                        Console.WriteLine("SendBarcode:{0}", isok);
                    }
                    catch(Exception ex)
                    {
                        Kuge.Message.PopupError(ex.Message, this);
                    }
                   
                }
                else
                {
                    Kuge.Message.PopupError(SR.BarcodeRuleError, this,3000);
                }
            }
        }
#endif

        #region 条码规则检查

        /// <summary>
        /// *:any;$:Letter;#:Number.e.g.:ABC####$$$$****789
        /// *:任何字符;$:必须是字母;#:必须是数字.e.g.:ABC####$$$$****789
        /// </summary>
        /// <param name="rule"></param>
        /// <param name="barcode"></param>
        /// <returns></returns>
        private bool BarcodeRuleCheck(string rule, string barcode)
        {
            bool isCorrect = true;

            if (string.IsNullOrEmpty(rule))
            {
                isCorrect = true;
            }
            else if (string.IsNullOrEmpty(barcode))
            {
                isCorrect = false;
            }
            else if (rule.Trim().Length != barcode.Trim().Length)
            {
                isCorrect = false;
            }
            else
            {
                #region 验证规则
                for (int i = 0; i < rule.Length; i++)
                {
                    if (i < barcode.Length)
                    {
                        char c = rule[i];
                        char b = barcode[i];
                        if (c == '*')
                        {
                        }
                        else if (c == '$')
                        {
                            //任意字母
                            if (!char.IsLetter(b))
                            {
                                isCorrect = false;
                            }
                        }
                        else if (c == '#')
                        {
                            //任意数字
                            if (!char.IsNumber(b))
                            {
                                isCorrect = false;
                            }
                        }
                        else
                        {
                            if (c != b)
                            {
                                isCorrect = false;
                            }
                        }
                    }
                }
                #endregion
            }

            return isCorrect;
        }

        #endregion

        #endregion

        #region Test Result

        /// <summary>
        /// Read data from Queue
        /// 从队列中读取一个测试结果
        /// </summary>
        /// <param name="itm"></param>
        /// <returns></returns>
        private bool ReadData(out DataItem itm)
        {
            return DataQueue.TryDequeue(out itm);
        }

        private Result GetResult(List<Result> ResultList, string Key)
        {
            foreach (Result v in ResultList)
            {
                if (v.Key == Key)
                {
                    return v;
                }
            }
            return null;
        }

        /// <summary>
        /// Saving Data here
        /// 用定时器定时处理队列中的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void T_Refresh_Tick(object sender, EventArgs e)
        {
            T_Refresh.Enabled = false;

            try
            {
                DataItem itm;

                if (ReadData(out itm))
                {
                    #region 先测试再扫码

                    if (mScanAfterTest.Checked)
                    {
                        frmBarcodeInput fBar = new frmBarcodeInput(this);
                        Barcode.Clear();
                        fBar.ShowDialog();

                        itm.Data.Barcode = Barcode.ToString();
                    }

                    #endregion

#if CUSTOM_UI

                    if((DataWindow!=null) && (DataWindow.IsDisposed==false))
                    {
                        Action<Testpad.BTS.Data> Op= new Action<Data>(DataWindow.Display);
                        Op.BeginInvoke(itm.Data, null, null);
                    }

#endif

                    #region SQL
#if SQL_ENABLE
                        if (Sql != null)
                        {
                            Sql.Start();
                            Sql.AppendWithName("Conclusion", itm.Data.AllPassed ? "PASSED" : "FAILED");
                            foreach (var v in itm.Data.Result)
                            {
                                switch (v.Flag)
                                {
                                    case "L":
                                    case "H":
                                    case "F":
                                        Sql.AppendWithKey(v.Key, v.Value);
                                        break;
                                    default:
                                        Sql.AppendWithKey(v.Key, v.Value);
                                        break;
                                }
                            }
                            Sql.Flush("TP_6000_Plus");
                        } 
#endif
                    #endregion

                    #region DEBUG
#if DEBUG && true
                    StringBuilder sb = new StringBuilder();
                    sb.AppendFormat("******************************************\r\n");
                    sb.AppendFormat("Device SN:{0}\r\n", itm.Tag.SN);
                    sb.AppendFormat("Passed or not:{0}\r\n", itm.Data.AllPassed);
                    sb.AppendFormat("PortName  :{0}\r\n", itm.Tag.PortName);
                    sb.AppendFormat("Channel  :{0}\r\n", itm.Tag.Channel);
                    sb.AppendFormat("Barcode:{0}\r\n", itm.Data.Barcode);
                    sb.AppendFormat("CellBarcode:{0}\r\n", itm.Data.CellBarcode);
                    sb.AppendFormat("ErrorCode:{0}\r\n", itm.Data.ErrorCode);
                    sb.AppendFormat("******************************************\r\n");
                    foreach (var v in itm.Data.Result)
                    {
                        sb.AppendFormat("[{0}]{1}:{2},{3} [{4},{5}]\r\n", v.Key, v.Name, v.Value, v.Flag, v.Minimum, v.Maximum);
                    }
                    Console.WriteLine(sb.ToString());
#endif

                    #endregion
                }

                #region 显示数据库计数
#if !CUSTOM_UI
#if SQL_ENABLE
                if (INI.Get<bool>(Kuge.Resources.Text.SQLServer, Kuge.Resources.Text.Enable, false.ToString()))
                {
                    if ((Sql == null) || (Sql.State != ConnectionState.Open))
                    {
                        BTS_Instance.AppendInformationItem(SR.InsertToSQL, SR.NotConnected, Color.Red);
                    }
                    else
                    {
                        BTS_Instance.AppendInformationItem(SR.InsertToSQL, Sql.Inserted, Color.Green);
                        if (Sql.Buffered > 3)
                        {
                            Kuge.Message.PopupError(SR.DataNotSave, this, 1000);
                        }
                    }
                }
                else
                {
                    BTS_Instance.AppendInformationItem(SR.InsertToSQL, SR.Disable, Color.Gray);
                } 
#endif
#endif
                #endregion
            }
            catch
            {
            }

            T_Refresh.Enabled = true;
        }
        #endregion

        #region Other

        private bool OutputSignale(string portname,bool passed)
        {
            return BTS_Instance.OutputSignal(portname, passed);
        }

        #endregion

        private void mTemperature_Click(object sender, EventArgs e)
        {
            OutputSignale(BTS_Instance.Ports[0], true);
        }
    }
}
